<?php
namespace app\index\controller;

use think\Controller;
use think\Request;
use think\Db;
use think\Session;
use app\index\common;

/**
 * 商户逻辑类
 */
class Business extends Controller
{
    public $user_id = 0;
    public $user = array();
    public $check_date = 0;
    
    public function _initialize() {      
        parent::_initialize();
        if(session('?user'))
        {
            $user = session('user');
            $user = Db::table('users')->where("id", $user['id'])->find();
            session('user',$user);  //覆盖session 中的 user               
            $this->user = $user;
            $this->user_id = $user['id'];
            $this->assign('user',$user); //存储用户信息
            $this->assign('user_id',$this->user_id);
        }
    }
    
    public function test_update_business_info() {
        return $this->fetch();
    }
    
    public function test_add_address(){
        return $this->fetch();
    }
    
    public function test_add_business() {
       return $this->fetch();
    }
    
    public function test_business_login() {
       return $this->fetch();
    }
    
    
    /**
    * 2018-4-9 日期格式
    * 曹振威 开发人
    * 新增商户地址   type = 0 收货地址   type = 1 退货地址   type = 2 自提地址
    * @return [type]      [函数简述]
    */
    public function add_address() {
        $address_insert = array();
        $user_id = $this->user_id;
        $name = input('name');
        $phone = input('phone');
        $landline = input('landline'); // 座机
        $province = input('province');
        $city = input('city');
        $area = input('area');
        $address = input('address');
        $type = input('type');  // 地址类型   0-收货 ; 1-退货
        
        if(!$name){
            $this->check_date = 1;
            $date = array('status'=>20016,'msg'=>'联系人不能为空','data'=>'');
        }elseif(!$phone && !$landline){
            $this->check_date = 1;
            $date = array('status'=>20017,'msg'=>'手机号和座机号必须填写至少一个','data'=>'');
        }elseif ($phone) {
            if(common::check_mobile($phone)['ErrorCode'] == 1){
                $this->check_date = 1;
                $date = array('code'=>20003,'msg'=>'手机号有误','data'=>'');
            }
        }elseif ($landline) {
            if(common::check_mobile(0,$landline)['ErrorCode'] == 2){
                $this->check_date = 1;
                $date = array('code'=>20003,'msg'=>'座机号有误','data'=>''); 
            }
        }elseif(!$province || !$city || !$area){
            $this->check_date = 1;
            $date = array('code'=>20016,'msg'=>'联系地址不能为空','data'=>'');
        }elseif (!$address) {
            $this->check_date = 1;
            $date = array('code'=>20016,'msg'=>'详细地址不能为空','data'=>'');
        }elseif(!$type){
            $this->check_date = 1;
            $date = array('code'=>20016,'msg'=>'地址类别不能为空','data'=>'');
        }
        
        if($this->check_date != 0){
            exit(json_encode($date));
        }
        
        $address_insert = [
            'user_id' => $user_id,
            'name' => $name,
            'phone' => $phone,
            'landline' => $landline,
            'province' => $province,
            'city' => $city,
            'area' => $area,
            'address' => $address,
            'type' => $type,
            'createtime' => date('Y-m-d H:i:s')
        ];
        
        if($address_insert){
            $row = Db::table('address')->insertGetId($address_insert);
            $data = Db::table('address')->where('user_id',$user_id)->field('name,landline,phone,province,city,area,address,type,state')->select();
            if($row > 0){
                $date = array('code'=>666,'msg'=>'新增地址成功','data'=>$data);
            }else{
                $date = array('code'=>20018,'msg'=>'新增地址失败','data'=>'');
            }
        }
        return $date;
    }
    
    /**
    * 2018-4-9 日期格式
    * 曹振威 开发人
    * 设置/修改店铺基本信息
    * @return [type]      [函数简述]
    */
    public function update_business_info() {
        $user_id = $this->user_id;
        $business_up = array();
        // 获取参数
        $business_name = input('business_name'); // 商户名称
        $business_hours = input('business_hours'); // 商户营业时间
        if($business_hours){
            $business_hours_arr = explode('-', $business_hours);
            $business_up['start_business_hours'] = $business_hours_arr[0];
            $business_up['stop_business_hours'] = $business_hours_arr[1];
        }
            $file_log_image = request()->file('log_image_url'); 
            if($file_log_image){
                $business_up['log_url'] = common::picture($file_log_image); 
            }
        $store_description = input('store_description'); // 商户简介
        if($business_name){
            $business_up['business_name'] = $business_name;
        }
        // 修改不为空的参数
        if($business_up){
            $row = Db::table('business')->where('business_id',$user_id)->update($business_up);
            $data = Db::table('business')->alias('a')->join('users u','a.business_id = u.id','LEFT')->field('a.log_url,a.business_name,a.business_phone,a.start_business_hours,a.stop_business_hours,a.store_description,a.is_auth,u.is_identity')->select();

            if($row){
                $date = array('code'=>666,'msg'=>'商户基本信息更新成功','data'=>$data);
            } else {
                $date = array('code'=>20015,'msg'=>'商户基本信息更新失败','data'=>'');
            }
        }
        return $date;
    }
    
    
    /**
    * 2018-4-8 日期格式
    * 曹振威 开发人
    * 商户登录验证
    * @param  $phone 
    * @param  $password 
    * @param  $system_id 
    * @return [type]      [函数简述]
    */
    public function login($phone,$password,$system_id){
    	$date = array();
        
        if(!$phone || !$password){
            $date = array('code'=>20010,'msg'=>'请填写账号或密码','data'=>'');
        }
        
        $user = Db::table('users')->where(['phone'=>$phone,'system_id'=>$system_id])->find();
        
        if(empty($user)){
           $date = array('code'=>20011,'msg'=>'该平台没有该用户!','data'=>'');
         }elseif($password != $user['password']){
           $date = array('code'=>20012,'msg'=>'密码错误!');
        }elseif($user['state'] == 1){
           $date = array('code'=>20013,'msg'=>'账号异常已被禁用！！！','data'=>'');
        }elseif($user['is_business'] == 0){
            $date = array('code'=>200014,'msg'=>'该用户是非商户','data'=>'');
        }else{
           $date = array('code'=>666,'msg'=>'登录验证成功','data'=>$user);
        }
        return $date;
    }
    
    /**
    * 2018-4-8 日期格式
    * 曹振威 开发人
    * 商户登录
    * @return [type]      [函数简述]
    */
    public function business_login() {
        $phone = input('post.phone');   
        $password = input('post.password'); 
        $system_id = input('post.system_id');
        $verify_code = input('post.verifyCode'); // 验证码
        if(!$phone || !$password || !$system_id || !$verify_code){
            $this->check_date = 1;
            $date = array('code'=>20006,'msg'=>'参数不能为空','data'=>'');
        }else{
            $capthcha=new \think\captcha\Captcha();
            if (!$capthcha->check($verify_code)){
                $this->check_date = 1;
                $date = array('code'=>20007,'msg'=>'验证码错误','data'=>'');
            }
        }
        if($this->check_date != 0){
            exit(json_encode($date));
        }
    	$res = $this->login($phone, $password,$system_id);

    	if($res['code'] == 666){
                $last_login_time = date('Y-m-d H:i:s');
                $row_login = db('users')->where('id',$res['data']['id'])->setField('last_login_time',$last_login_time);
                $data = db('users')->field('id,system_id,is_business,name,state,grade,agent,shop,is_staff,is_address,phone,card_balance,enjoy_currency,createtime,last_login_time')->where(['phone'=>$phone,'system_id'=>1])->select();
                if($data){
                    $token = md5($data[0]['id']. session_id(). time());
                    $row = Db::table('token')->insert(['token_value'=>$token,'add_time'=>time()]);
                    if(!$row){
                        $date = array('code'=>20008,'msg'=>'token生成失败','data'=>'','user_id'=>$data['id']);
                    }
                    $data[0]['token'] = $token;
                    session('user',$data[0]);
                    setcookie('uid',$data[0]['id'],null,'/');
                    setcookie('is_business',$data[0]['is_business'],null,'/');  // 是否是商家
                    setcookie('cn',0,time()-3600,'/');
                    $date = array('code'=>666,'msg'=>'登录成功','data'=>$data);
                }else{
                    $date = array('code'=>20009,'msg'=>'登录失败，请重新登录','data'=>'');
                }
    	}else{
           return $res;    
        }
    	return $date;
    }
    
    /**
    * 2018-4-8 日期格式
    * 曹振威 开发人
    * 更新users表
    * @return [type]      [函数简述]
    */
    public function update_users($phone,$system_id=1){
        $user = Db::table('users')->where(['phone'=>$phone,'system_id'=>$system_id])->find(); 
        if($user){
            if($user['is_business'] != 0){
                $date = array('code'=>20005,'msg'=>'该用户已经是商户','data'=>'');
                exit(json_encode($date));
            } else {
                $date =  Db::table('users')->where('phone',$phone)->setField('is_business',1); // 改成商户后，改变等级为父级  
            } 
        }else{
            $user_insert = [
                'system_id' => $system_id,
                'is_business' => 1,
                'phone' => $phone,
                'createtime' => date('Y-m-d H:i:s')
            ];
            if($user_insert){
                $row = Db::table('users')->insertGetId($user_insert);
                $date = Db::table('users')->where('id',$row)->find();
            } else {
                $date = array('code'=>20001,'msg'=>'用户插入数据有错误','data'=>'');
            }
        }
       return $date;
    }
    
    
    /**
    * 2018-4-8 日期格式
    * 曹振威 开发人
    * 添加商户
    * @return [type]      [函数简述]
    */
    public function add_business (){
            $date = array();
            $system_id = input('system_id',1);
            $business_name = input('business_name'); // 商家名称
            $business_phone = input('business_phone'); // 商家联系电话
            $business_address = input('business_address'); // 商户详细地址
            $file_log_image = request()->file('log_image_url'); // 商家logo
            $phone = common::check_mobile($business_phone);
            if($phone['ErrorCode'] == 1){ 
                $this->check_date = 1;
                $date = array('code'=>20003,'msg'=>$phone['ErrorMessage'],'data'=>'');
            }
            $log_image_url = common::picture($file_log_image); 
            if($this->check_date != 0){
                exit(json_encode($date));
            }
            $add_insert = [
                'business_name' => $business_name,
                'business_address' => $business_address,
                'log_url' => $log_image_url,
                'createtime' => date('Y-m-d H:i:s')
            ];
            
        if($add_insert){
            $row_in = db('business')->insertGetId($add_insert);
            if($row_in){
                $user_id = $this->update_users($business_phone,$system_id);
                if($user_id){ 
                    $row_up = Db::table('business')->where('id',$row_in)->setField('business_id',$user_id['id']);           
                    if($row_up){  
                        $data = db('business')->where('id',$row_in)->find();
                        $date = array('code'=>666,'msg'=>'更新商户成功','data'=>$data);
                    }else{
                        $date = array('code'=>20004,'msg'=>'更新商户不成功','data'=>'');
                    }
                }
            }else{
                $date = array('code'=>20002,'msg'=>'商户插入数据不成功','date'=>'');
            }
        }else{
            $date = array('code'=>20001,'msg'=>'商户插入的数据有误','date'=>'');
        }
        return $date;
    }
    
}

